#include "nemu.h"
#include <stdlib.h>
#include <time.h>

CPU_state cpu;

const char *regsl[] = {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"};
const char *regsw[] = {"ax", "cx", "dx", "bx", "sp", "bp", "si", "di"};
const char *regsb[] = {"al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"};

//测试寄存器结构
void reg_test()
{
	srand(time(0));
	uint32_t sample[8];
	uint32_t eip_sample = rand();
	cpu.eip = eip_sample;

	int i;
	for (i = R_EAX; i <= R_EDI; i++)
	{
		sample[i] = rand();
		reg_l(i) = sample[i];
		assert(reg_w(i) == (sample[i] & 0xffff));
	}

	assert(reg_b(R_AL) == (sample[R_EAX] & 0xff));
	assert(reg_b(R_AH) == ((sample[R_EAX] >> 8) & 0xff));
	assert(reg_b(R_BL) == (sample[R_EBX] & 0xff));
	assert(reg_b(R_BH) == ((sample[R_EBX] >> 8) & 0xff));
	assert(reg_b(R_CL) == (sample[R_ECX] & 0xff));
	assert(reg_b(R_CH) == ((sample[R_ECX] >> 8) & 0xff));
	assert(reg_b(R_DL) == (sample[R_EDX] & 0xff));
	assert(reg_b(R_DH) == ((sample[R_EDX] >> 8) & 0xff));

	assert(sample[R_EAX] == cpu.eax);
	assert(sample[R_ECX] == cpu.ecx);
	assert(sample[R_EDX] == cpu.edx);
	assert(sample[R_EBX] == cpu.ebx);
	assert(sample[R_ESP] == cpu.esp);
	assert(sample[R_EBP] == cpu.ebp);
	assert(sample[R_ESI] == cpu.esi);
	assert(sample[R_EDI] == cpu.edi);

	assert(eip_sample == cpu.eip);
}

//用于从给定的寄存器名称字符串（s）中查找对应的寄存器值。如果找到匹配的寄存器名称，它返回相应的寄存器值，并设置success为true。如果找不到匹配的寄存器名称，则设置success为false并返回0
uint32_t get_reg_val(const char *s, bool *success)
{
	int i;
	*success = true; // 初始化success为true，假设找到匹配的寄存器名称

	// 查找32位寄存器名称
	for (i = 0; i < 8; i++)
	{
		if (strcmp(regsl[i], s) == 0) // 如果找到匹配的32位寄存器名称
		{
			return reg_l(i); // 返回对应32位寄存器的值
		}
	}

	// 查找16位寄存器名称
	for (i = 0; i < 8; i++)
	{
		if (strcmp(regsw[i], s) == 0) // 如果找到匹配的16位寄存器名称
		{
			return reg_w(i); // 返回对应16位寄存器的值
		}
	}

	// 查找8位寄存器名称
	for (i = 0; i < 8; i++)
	{
		if (strcmp(regsb[i], s) == 0) // 如果找到匹配的8位寄存器名称
		{
			return reg_b(i); // 返回对应8位寄存器的值
		}
	}

	// 检查是否为eip寄存器
	if (strcmp("eip", s) == 0)
	{
		return cpu.eip; // 返回eip寄存器的值
	}

	*success = false; // 如果没有找到匹配的寄存器名称，设置success为false
	return 0; // 返回0表示未找到匹配
}

